<template>
  <div class="common-list-view__v2">
    <div class="common-list-view-header__v2 a-center mb_12">
      <div class="common-list-view-header__v2-left">
        <!-- <el-button type="plain-third" @click="deleteHandler">
          <i class="iconfont icon-delete"></i>{{ $t('common.base.delete') }}
        </el-button> -->
      </div>
      <div class="common-list-view-header__v2-right">
        <!-- <el-dropdown>
          <span class="el-dropdown-link cur-point acenter">
            {{ $t('common.base.moreOperator') }}
            <i class="iconfont icon-fdn-select ml_4"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <div class="import-task">
                {{$t('common.base.import')}}
                <div class="import-task-item import-item">
                  <div v-for="(item, index) in taskManageTypeList" :key="index" @click="importHandler(item.id)">
                    {{ item.name }}
                  </div>
                </div>
              </div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown> -->

        <div class="el-dropdown-link cur-point acenter" @click="handleSelectColumn">
          {{ $t('common.base.choiceCol') }}
          <i class="iconfont icon-fdn-select ml_4"></i>
        </div>
      </div>
    </div>

    <el-table
      v-if="columns.length"
      v-table-style
      v-loading="loading"
      ref="tableComponentRef"
      header-row-class-name="common-list-table-header__v2"
      class="bbx-normal-list-box"
      :data="dataList"
      :height="tableContainerHeight"
      @select="handleSelection($event, dataList)"
      @select-all="handleSelection($event, dataList)"
      @header-dragend="handlerHeaderDragend"
      @sort-change="handlerSortChanged"
      stripe
      border
    >
      <el-table-column type="selection" width="48" align="center"></el-table-column>
      <template v-for="column in columns">
        <el-table-column
          v-if="column && column.show"
          :align="column.align"
          :key="column.field"
          :label="column.displayName"
          :prop="column.field"
          :width="column.width || 160"
          :min-width="column.minWidth"
          :sortable="column.sortable"
          :fixed="column.fixLeft || false"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <!-- 编号 -->
            <template v-if="column.field === 'missionNo'">
              <div class="view-detail-btn" @click="openTaskManageViewTab({...scope.row, taskFormId:scope.row.templateId})">{{ scope.row.taskNumber }}</div>
            </template>

            <!-- 任务名称 -->
            <template v-if="column.field === 'missionName'">
              <div class="align-items-center">
                {{ scope.row.taskName }} 
                <ProjectTaskLabel class="ml_8" :current-row-data="scope.row"/>
              </div>
              
            </template>

            <!-- 负责人 -->
            <template v-if="column.field === 'managerPerson' && scope.row.managerList">
              <span>
                <template v-for="(item, index) in scope.row.managerList">
                
                  <span v-if="index !== 0">，</span>
                  <template v-if="isOpenData">
                    <open-data type="userName" :openid="item.staffId"></open-data>
                  </template>
                  <template v-else>
                    {{item.displayName}}
                  </template>
                
                </template>
              </span>
            </template>

            <!-- 任务内容 -->
            <template v-if="column.field === 'missionContent'">
              {{ scope.row.taskDesc }}
            </template>

            <!-- 任务状态 -->
            <template v-else-if="column.field === 'taskStatus'">
              <span class="status-tag" :style="stateBGC(scope.row.taskStatus)">
                {{ formatStatus(scope.row.taskStatus) }}
              </span>
            </template>

            <!-- 任务类型 -->
            <template v-else-if="column.field === 'taskType'">
              <span>{{ taskTypeMap[scope.row.taskType] || '' }}/{{ scope.row.taskFormName }}</span>
            </template>

            <!-- 项目进度 -->
            <template v-else-if="column.field === 'taskProgress'">
              <el-progress :percentage="scope.row.taskProgress" class="table-blacklist"></el-progress>
            </template>
            
            <!-- 前置任务 -->
            <template v-else-if="column.field === 'preTaskInfoList'">
              {{ formatreTaskInfoList(scope.row.preTask) }}
            </template>
            
            <!-- 预计工时 -->
            <template v-else-if="column.field === 'expectTime'">
              {{ formatreTaskInfoList(scope.row.expectWorkTime) }}
            </template>

            <template v-else-if="column.field === 'planStartTime'" >
              {{scope.row.planStartTime | fmt_date}}
            </template>

            <template v-else-if="column.field === 'planEndTime'" >
              {{scope.row.planEndTime | fmt_date}}
            </template>

            <template v-else-if="column.field === 'projectNumber'" >
              <div class="view-detail-btn" @click="openProjectViewTab(scope.row)">{{ scope.row.projectNumber }}</div>
            </template>

            <template v-else>
              {{ $formatFormField(column, scope.row) }}
            </template>
          </template>
        </el-table-column>
      </template>
      
      <el-table-column fixed="right" :label="$t('common.base.operation')" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="openTaskManageViewTab({...scope.row, taskFormId:scope.row.templateId})">{{ $t('common.base.detail') }}</el-button>
        </template>
      </el-table-column>

      <template slot="empty">
        <BaseListForNoData  v-show="!loading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
      </template>
    </el-table>

    <!-- 分页 S -->
    <div class="table-footer bbx-normal-table-footer-10">
      <div class="list-info">
        <i18n path="common.base.table.totalCount">
          <span place="count" class="level-padding">{{ dataListPageInfo.total || 0 }}</span>
        </i18n>

        <template v-if="multipleSelection.length > 0">
          <i18n path="common.base.table.selectedNth">
            <span place="count" class="color-primary pad-l-5 pad-r-5">{{ multipleSelection.length }}</span>
          </i18n>
          <span class="color-primary pad-l-5 cur-point" @click="clearSelection">{{ $t('common.base.clear') }}</span>
        </template>
      </div>

      <el-pagination
        background
        @current-change="handlePageNumChange"
        @size-change="handleSizeChange"
        :page-sizes="defaultTableData.defaultPageSizes"
        :page-size="searchParams.pageSize"
        :current-page="searchParams.pageNum"
        layout="prev, pager, next, sizes, jumper"
        :total="dataListPageInfo.total"
      >
      </el-pagination>
    </div>
    <!-- 分页 E -->

    <!-- s 导入 -->
    <base-import
      ref="importModalRef"
      :title="$t('common.base.import')"
      :action="`/excels/paas/form/import?formTemplateId=${importTypeId}`"
      :template-url="`/api/paas/outside/pc/form/excel/import/template?formTemplateId=${importTypeId}`"
    ></base-import>
    <!-- e 导入 -->
  </div>
</template>

<script>
/* model */
import { ViewTypeComponentNameEnum, taskTypeMap } from '@src/modules/projectManage/taskManageList/model';
import { DELETE_SUCCESS_MESSAGE, PLEASE_SELECT_DATA_MESSAGE } from '@src/model/const/Alert';
/* util */
import Platform from '@src/util/platform';
import Log from '@src/util/log';
import { t } from '@src/locales';
import _ from 'lodash';
import { formatStatus, stateBGC } from '@src/modules/projectManage/taskManageList/util/index';
import { defaultTableData } from '@src/util/table'
/* hooks */
import { useTable } from '@src/modules/projectManage/projectManageList/hooks/useTable';
import { useOpenTab } from '@src/modules/projectManage/taskManageList/hooks/useOpenTab';
import { useFetchTaskManageTableList } from '@src/modules/projectManage/taskManageList/hooks/useFetch';
/* vue */
import { ref, reactive, onMounted, watch } from 'vue';
/** component */
import ProjectTaskLabel from '@src/modules/projectManage/components/projectTaskLabel.vue'

export default {
  name: ViewTypeComponentNameEnum.Table,
  props: {
    columns: {
      type: Array,
      default: () => ([])
    },
    params: {
      type: Object,
      default: () => ({})
    },
    taskManageTypeList: {
      type: Array,
      default: () => ([])
    }
  },
  components: {
    ProjectTaskLabel
  },
  setup(props, { emit }) {
    const { tableComponentRef, multipleSelection, selectedIds, handleSelection, clearSelection, matchSelected, disposeHeaderDragendColumns, disposeTableSortChanged } = useTable();
    const { loading, dataList, dataListPageInfo, fetchTaskManageTableList } = useFetchTaskManageTableList();
    const { openTaskManageViewTab, openProjectViewTab } = useOpenTab();
    
    // 导入组件ref
    const importModalRef = ref(null);
    // 导入类型id
    const importTypeId = ref('');
    // 表格高度
    const tableContainerHeight = ref('calc(100% - 100px)');

    // 搜索参数
    const searchParams = reactive({
      pageSize: 10,
      pageNum: 1,
      asc: null,
      column: '',
    })

    // 选择列
    const handleSelectColumn = () => {
      emit('handleSelectColumn');
    }

    // 表头拖动列改变宽度
    const handlerHeaderDragend = (newWidth, oldWidth, column) => {
      disposeHeaderDragendColumns(newWidth, column, props.columns, ViewTypeComponentNameEnum.Table);
    }

    // 表格排序变化事件
    const handlerSortChanged = (option) => {
      const { column, asc } = disposeTableSortChanged(option);
      searchParams.column = column;
      searchParams.asc = asc;
      
      search();
    }

    // 删除事件
    const deleteHandler = async () => {
      if (!selectedIds.value.length) return Platform.alert(PLEASE_SELECT_DATA_MESSAGE);

      try {
        // 获取删除提示
        const confirm = await Platform.confirm(t('common.base.tip.confirmDeleteTip'));
        if (!confirm) return;
        
        // 删除
        console.log(selectedIds.value, 'selectedIds.value');
        
        Platform.alert(DELETE_SUCCESS_MESSAGE);
        clearSelection();
        
      } catch (error) {
        Log.error(error, deleteHandler.name);
      }
    }

    // 导入
    const importHandler = (id) => {
      importTypeId.value = id;
      importModalRef.value?.open();
    }

    // 搜索
    const search = (isRefresh) => {
      // 需要刷新
      if (isRefresh) return handlePageNumChange(1);
      
      const params = {
        ...searchParams,
        ...props.params
      }

      console.log('表格----构建参数', params)
      fetchTaskManageTableList(params);
    }

    // 页码跳转
    const handlePageNumChange = (pageNum) => {
      searchParams.pageNum = pageNum;
      dataList.value = [];
      search();
    }

    // 分页条数改变
    const handleSizeChange = (pageSize) => {
      searchParams.pageSize = pageSize;
      searchParams.pageNum = 1;
      search();
    }

    // 监听列表数据 把选中的匹配出来
    watch(dataList, (newValue) => {
      matchSelected(newValue);
    })

    // 前置任务
    const formatreTaskInfoList = (list) => {
      if(!list || !list.length) return list;
      
      return list.map(x=>x.name).join('，');
    }

    onMounted(() => {
      search(true);
    })

    return {
      defaultTableData,
      loading,
      dataList,
      dataListPageInfo,
      tableContainerHeight,
      searchParams,
      importModalRef,
      importTypeId,
      
      tableComponentRef,
      multipleSelection,
      handleSelection,
      clearSelection,
      handlerHeaderDragend,
      handlerSortChanged,

      handleSelectColumn,
      openTaskManageViewTab,
      openProjectViewTab,
      deleteHandler,
      importHandler,
      handlePageNumChange,
      handleSizeChange,
      search,

      formatStatus,
      formatreTaskInfoList,
      taskTypeMap,
      stateBGC,
    };
  },
};
</script>

<style lang="scss" scoped>
.common-list-view__v2 {
  height: 100%;
}

.import-task {
  position: relative;
  left: -15px;
  padding-left: 15px;

  &:hover &-item {
    display: block;
  }

  &-item {
    position: absolute;
    background: #fff;
    color: $text-color-primary;
    left: -115px;
    top: -8px;
    border: 1px solid #eee;
    border-radius: 4px;
    max-height: 50vh;
    overflow-y: auto;
    display: none;

    >div {
      padding: 4px 15px;
      width: 120px;
      word-break: break-all;

      &:hover {
        background-color: $color-regular;
        color: #77c5c3;
      }
    }
  }
}

.el-table {
  .status-tag {
    padding: 0 8px;
    background-color: $color-ding-blue;
    line-height: 22px;
    border-radius: 22px;
    color: #fff;
    font-size: 12px;
  }

  .el-progress {
    width: 100%;
  }
}
</style>

